<?php
/* wwwschool project

Copyright (C) 2009  Phillip Aldridge
Email : info@imi21.com
Web site http://www.imi21.com

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

/**
 *  File : login.php
 */  

require_once '../includes/config.php';

$date=date("Y-m-d H:i:s");
$logged = false;


if ( isset( $_POST['f'] ) &&  ( $_POST['f'] == 'logging' ))
{// user is logging in

  if ( isset( $_POST['password'] ) && isset( $_POST['email'] ) )
  {
    $db=new WS3_Database();
    $email = $db->makeSafeString( $_POST['email'] );
    $password = $db->makeSafeString( $_POST['password'] );
    $q="SELECT `id`, `user_type`, `first_name`, `last_name` FROM `user`
      WHERE `password`=MD5($password) AND `email`='$email'
      AND `active`='1'
      LIMIT 1";

      if ($db->query($q) && $db->nextRecord() )
      { // user does exist
        // update profile information

        $q="UPDATE `user` SET
        `last_login`='$date'
        WHERE  `id`='". $db->f('id') ."'' LIMIT 1";
        $dbUpdate = new WS3_Database();
        $dbUpdate->query($q);
        
        // now open a valid session
        $session->setValid( $db->f('id'), $db->f('user_type'),$db->f('first_name'),$db->f('last_name') );
        $logged = true;
      }else{
        $logged = false;
      }
    }else
    {
      $logged = false;
      //if (isset( $_SESSION['user'] ) ) $_SESSION['user']=null;
    }
}



if ($logged )
{
  header('location: index.php');
}else
{
  // display login page
  include WS3_TEMPLATE."header.php"; 
  
  if ($session->isValid() == false ) $t="FALSE"; else $t="TRUE";;
  
  require '../includes/classes/WS3formview.php';

  $form = new WS3_FormView('login');
  $form->setTitle( 'Login' );
  $form->displayResetButton( true );
  $form->setAction( 'login.php' );
  $form->addHiddenField( 'f', 'logging' ); // which function to call
  
  $form->addFieldSet( 'user', 'User');
  $form->addTextField( 'user','Email','email','email',"" );
  $form->addPasswordField( 'user','Password','password','password',"");
  
  $form->addFieldSet( 'info', 'Information');
  $form->addParagraph( 'info','<a href="login-password.php">Click here to retrive lost password</a>');
  echo $form->displayHTML();

  include WS3_TEMPLATE."footer.php";
}
?>